<template>
	<!-- 空状态 -->
	<view v-if="cart.length === 0" class="empty-container">
		<view class="empty-image">
			<img src="/img/暂无商品.svg" alt="空购物车" class="cart-image" />
		</view>
		<view class="empty-text">
			<text>购物车竟然是空的</text>
		</view>
		<view class="empty-hint">
			<text>快去挑选心仪的商品吧~</text>
		</view>
		<view class="empty-action">
			<wd-button type="primary" plain round @click="GotoHome">去首页逛逛</wd-button>
		</view>
	</view>

	<!-- 购物车列表 -->
	<view v-else class="cart-list">
		<view v-for="(item, idx) in cart" :key="item.id" class="cart-item">
			<checkbox :checked="item.checked" @click="toggleCheck(idx)" />
			<image :src="item.thumb_path || '/static/logo.png'" class="cart-img" mode="aspectFill"/>
			<view class="cart-info">
				<text class="cart-title">{{ item.title }}</text>
				<view class="cart-row">
					<text class="cart-price">¥{{ item.sell_price }}</text>
				</view>
				<!-- 数量操作单独一行 -->
				<view class="cart-row">
					<view class="num-ctrl">
						<view class="num-btn" :class="{disabled: item.count<=1}" @click="changeCount(idx, -1)">-</view>
						<text class="count">{{ item.count }}</text>
						<view class="num-btn" @click="changeCount(idx, 1)">+</view>
					</view>
				</view>
			</view>
			<!-- 删除按钮绝对定位在右下角 -->
			<view class="del-btn" @click="removeItem(idx)">删除</view>
		</view>
		<!-- 底部操作栏 -->
		<view class="cart-footer">
			<checkbox :checked="isAllChecked" @click="toggleAllCheck" /> 全选
			<text class="footer-info">
				已选 <text class="footer-num">{{ checkedCount }}</text> 件，
				合计 <text class="footer-price">¥{{ checkedTotal }}</text>
			</text>
			<button class="order-btn" :disabled="checkedCount===0" @click="gotoOrder">去结算</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { request, BASE_URL } from '@/Requset/request'

const cart = ref<any[]>([])

onShow(() => {
  const cartList = uni.getStorageSync('cartList') || []
  if (cartList.length === 0) {
    cart.value = []
    return
  }
  const ids = cartList.map(i => i.id).join(',')
  request({
    url: BASE_URL + `api/getshopcarlist/${ids}`,
    header: {
      token: uni.getStorageSync('token') || ''
    }
  }).then((res: any) => {
    if (res.data && res.data.status === 0) {	
      const detailList = res.data.message || []
      detailList.forEach(item => {
        const found = cartList.find(i => String(i.id) === String(item.id))
        item.count = found ? found.count : 1
        item.checked = true // 默认全选
      })
      cart.value = detailList
    } else if (res.statusCode === 401) {
		uni.showToast({ title: '请先登录', icon: 'none' })
		uni.navigateTo({
			url: `/pages/Login/Login?redirect=${encodeURIComponent(getCurrentPages().slice(-1)[0].route)}`
		})
    
    } else {
      cart.value = []
    }
  })
})

// 单选
function toggleCheck(idx: number) {
  cart.value[idx].checked = !cart.value[idx].checked
}
// 全选
const isAllChecked = computed(() => cart.value.length > 0 && cart.value.every(i => i.checked))
function toggleAllCheck() {
  const checked = !isAllChecked.value
  cart.value.forEach(i => i.checked = checked)
}
// 数量加减
function changeCount(idx: number, delta: number) {
  const item = cart.value[idx]
  if (item.count + delta < 1) return
  item.count += delta
  // 同步本地cartList
  const cartList = uni.getStorageSync('cartList') || []
  const found = cartList.find(i => String(i.id) === String(item.id))
  if (found) found.count = item.count
  uni.setStorageSync('cartList', cartList)
}
// 删除
function removeItem(idx: number) {
  // 先移除页面数据
  const id = cart.value[idx].id
  cart.value.splice(idx, 1)
  // 同步本地cartList
  let cartList = uni.getStorageSync('cartList') || []
  cartList = cartList.filter(i => String(i.id) !== String(id))
  uni.setStorageSync('cartList', cartList)
}
// 统计
const checkedCount = computed(() => cart.value.filter(i => i.checked).reduce((sum, i) => sum + i.count, 0))
const checkedTotal = computed(() => cart.value.filter(i => i.checked).reduce((sum, i) => sum + i.count * i.sell_price, 0))
// 跳转订单页
function gotoOrder() {
  const checkedGoods = cart.value.filter(i => i.checked)
  if (checkedGoods.length === 0) {
    uni.showToast({ title: '请选择商品', icon: 'none' })
    return
  }
  // 生成订单号
  const now = new Date()
  const orderId = 'OD' + now.getFullYear() + (now.getMonth()+1).toString().padStart(2,'0') + now.getDate().toString().padStart(2,'0') + now.getHours().toString().padStart(2,'0') + now.getMinutes().toString().padStart(2,'0') + now.getSeconds().toString().padStart(2,'0') + Math.floor(Math.random() * 1000)
  // 生成下单时间
  const orderTime = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2,'0')}-${now.getDate().toString().padStart(2,'0')} ${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}:${now.getSeconds().toString().padStart(2,'0')}`
  // 计算总价
  const totalPrice = checkedGoods.reduce((sum, i) => sum + i.count * i.sell_price, 0)
  // 保存到本地
  uni.setStorageSync('orderGoods', checkedGoods)
  uni.setStorageSync('orderId', orderId)
  uni.setStorageSync('orderTime', orderTime)
  uni.setStorageSync('orderTotalPrice', totalPrice)
  uni.navigateTo({ url: '/pages/Order_page/Order_page' })
}

function GotoHome() {
  uni.switchTab({
    url: '/pages/index/index'
  });
}
</script>

<style lang="scss" scoped>
@import '@/common/common.scss';

:host, page, .shopping-root {
  background: #ededed !important;
  min-height: 100vh;
  width: 100vw;
  display: block;
}

.empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: #{px2rpx(50)} #{px2rpx(20)};
    height: 100vh;
    box-sizing: border-box;
    background-color: #f7f7f7;
}

.empty-image {
    margin-bottom: #{px2rpx(20)};
}

.cart-image {
    width: #{px2rpx(150)};
    height: #{px2rpx(150)};
    opacity: 0.6;
}

.empty-text {
    font-size: #{px2rpx(18)};
    color: #333;
    margin-bottom: #{px2rpx(10)};
    font-weight: bold;
}

.empty-hint {
    font-size: #{px2rpx(14)};
    color: #999;
    margin-bottom: #{px2rpx(30)};
}

.empty-action {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 #{px2rpx(40)};
    box-sizing: border-box;
}

.empty-action .wd-button {
    width: 100%;
    max-width: #{px2rpx(300)};
    height: #{px2rpx(40)};
    font-size: #{px2rpx(16)};
    margin: 0 auto;
    display: block;
}

.cart-list {
  width: 100%;
  padding: 24rpx 0 120rpx 0;
  box-sizing: border-box;
  background: transparent; // 继承灰色
}

.empty {
  text-align: center;
  font-size: #{px2rpx(16)};
  color: #999;
  padding: #{px2rpx(50)} 0;
}

.cart-item {
  position: relative;
  display: flex;
  align-items: flex-start;
  margin: 32rpx 24rpx 0 24rpx; /* 增大间距更美观 */
  padding: 32rpx 24rpx 24rpx 24rpx; /* 上方多留空间 */
  border-radius: 20rpx;
  background: #fff;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.08);
  min-height: 140rpx;
}

.cart-img {
  width: 110rpx;
  height: 110rpx;
  margin-right: 22rpx;
  border-radius: 14rpx;
  background: #f5f5f5;
  object-fit: cover;
}

.cart-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 10rpx;
  min-height: 110rpx;
}

.cart-title {
  font-size: 32rpx;
  color: #222;
  font-weight: bold;
  margin-bottom: 6rpx;
  line-height: 1.3;
}

.cart-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 8rpx;
  gap: 24rpx;
}

.cart-price {
  color: #e64340;
  font-size: 30rpx;
  font-weight: bold;
  margin-top: 6rpx;
}

.num-ctrl {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 24rpx;
  padding: 0 14rpx;
  height: 48rpx;
  gap: 10rpx;
  margin: 0;
}

.num-btn {
  width: 44rpx;
  height: 44rpx;
  background: #fff;
  font-size: 32rpx;
  border-radius: 50%;
  line-height: 44rpx;
  color: #333;
  text-align: center;
  user-select: none;
  border: 1rpx solid #eee;
}
.num-btn.disabled {
  color: #ccc;
  pointer-events: none;
  border: 1rpx solid #f5f5f5;
}

.count {
  font-size: 28rpx;
  width: 44rpx;
  text-align: center;
}

.del-btn {
  position: absolute;
  right: 24rpx;
  bottom: 24rpx;
  background: #ffeded;
  color: #e64340;
  border-radius: 24rpx;
  padding: 0 28rpx;
  height: 48rpx;
  font-size: 28rpx;
  box-shadow: 0 2rpx 8rpx rgba(230,67,64,0.08);
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
  cursor: pointer;
}

.cart-footer {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  background: #ededed;
  border-top: 1rpx solid #e0e0e0;
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0,0,0,0.05);
  z-index: 99;
  gap: 16rpx;
}

.footer-info {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  margin-left: 24rpx;
}

.footer-num, .footer-price {
  color: #e64340;
  font-weight: bold;
}

.order-btn {
  background: #e64340;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;
  padding: 0 36rpx;
  height: 64rpx;
}
</style>